package com.education.welco.controller;

import com.alibaba.fastjson.JSONObject;
import com.education.auth.entity.UserInfo;
import com.education.common.pojo.AjaxResult;
import com.education.demouse.service.IStudentAnswerDetailsService;
import com.education.utils.JwtUtil;
import com.education.websocket.data.HomeBuffer;
import com.education.websocket.data.HomeData;
import com.education.websocket.server.WebSocketServerWELCO;
import com.education.welco.pojo.*;
import com.education.welco.pojo.vo.ClassPaper;
import com.education.welco.pojo.vo.*;
import com.education.welco.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * 教师批阅模块  (试卷批阅、作业批阅)
 */
@RestController
@RequestMapping("/teacherReviews")
public class TeacherReviewsController {

    @Autowired
    private ISCatalogWorkService catalogWorkService;
    @Autowired
    private OrderPaperService orderPaperService;
    @Autowired
    private OrderAnswerService orderAnswerService;
    @Autowired
    private OrderUserPaperService orderUserPaperService;
    @Autowired
    private IStudentAnswerDetailsService studentAnswerDetailsService;
    @Autowired
    private ITStudentService studentService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HomeBuffer homeBuffer;

    /**
     * 查询具体代课老师试卷列表  当前代课老师出的试卷列表(可能分享出去，可能没有分享出去)  根据老师的id去查
     *
     * @param teaId      老师id
     * @param paperName  试卷名称
     * @param examStatus 考试状态   0未开始.1进行中.2已完成
     * @return
     */
    @GetMapping("/paperListByTeacher")
    public AjaxResult paperListByTeacher(@RequestParam(value = "teaId", required = false) Integer teaId,
                                         @RequestParam(value = "paperName", required = false) String paperName,
                                         @RequestParam(value = "examStatus", required = false) Integer examStatus,
                                         @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                         @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        /**
         * 老师带课表(老师id-课程id-classId)-试卷表(课程id-试卷id)-学生答题表
         * 根据参数查询得到的试卷列表   orderPaper表查试卷列表
         */
        List<OrderPaper> orderPaperList = orderPaperService.paperListByTeacher(teaId, paperName, examStatus, pageNum, pageSize);
        //查找试卷关联的班级
        for (OrderPaper orderPaper : orderPaperList) {
            //课程id-classId 没有分享表的逻辑
            List<TClass> tClasses = orderPaperService.selectClassByTopCatalogId(orderPaper.getTopCatalogId());
            if (tClasses.size() > 0) {
                //设置考试班级
                StringBuffer tClassNames = new StringBuffer();
                //班级id数组集合
                List<Integer> classIdList = new ArrayList<>();
                for (TClass tClass : tClasses) {
                    tClassNames.append(tClass.getClassName() + ",");
                    classIdList.add(tClass.getId());
                }
                if (tClassNames.length() > 0) {
                    tClassNames.deleteCharAt(tClassNames.length() - 1);
                }
                orderPaper.setTClassNames(tClassNames.toString());
                //设置考生人数(查找)  如果classIdList不为空
                Integer studentNum = studentService.selectStudentNumByClassId(classIdList);
                orderPaper.setClassSize(studentNum);
                //考生已提交试卷数量  统计试卷id的个数
                Integer commitPaperNum = orderUserPaperService.selectCommitPaperNum(orderPaper.getId());
                orderPaper.setSubmitnum(commitPaperNum);
            }
        }
        PageInfo<OrderPaper> orderPaperPageInfo = new PageInfo<>(orderPaperList);
        return AjaxResult.success(orderPaperPageInfo);
    }

    /**
     * 班级id和名称下拉列表获取  批改试卷
     *
     * @param topCatalogId 课程id
     * @return
     */
    @GetMapping("/classIdAndName")
    public AjaxResult classIdAndName(@RequestParam(value = "topCatalogId", required = false) Integer topCatalogId) {
        List<TClass> tClasses = orderPaperService.selectClassByTopCatalogId(topCatalogId);
        return AjaxResult.success(tClasses);
    }

    /**
     * 根据班级查找试卷列表进行批阅
     *
     * @param paperId
     * @param classId
     * @param readState 批改状态 1已批阅  2未批阅
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/classPaperList")
    public AjaxResult classPaperList(@RequestParam(value = "paperId", required = false) Integer paperId,
                                     @RequestParam(value = "classId", required = false) Integer classId,
                                     @RequestParam(value = "readState", required = false) Integer readState,
                                     @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                     @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        List<ClassPaper> classPaperList = orderUserPaperService.classPaperList(paperId, classId, readState, pageNum, pageSize);
        PageInfo<ClassPaper> classPaperPageInfo = new PageInfo<>(classPaperList);
        return AjaxResult.success(classPaperPageInfo);
    }

    /**
     * 查试卷的详细情况   试卷id 用户id
     *
     * @param paperId
     * @param userId
     * @return
     */
    @GetMapping("/resdQuestionList")
    public AjaxResult resdQuestionList(@RequestParam(value = "paperId", required = false) Integer paperId,
                                       @RequestParam(value = "userId", required = false) Integer userId) {
        Map<String, Object> resultMap = new HashMap<>();
        //查找试卷信息
        OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
        Map<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("singleScore", orderPaper.getSingleScore());
        stringStringHashMap.put("manyScore", orderPaper.getManyScore());
        stringStringHashMap.put("judgmentScore", orderPaper.getJudgmentScore());
        stringStringHashMap.put("answSore", orderPaper.getAnswSore());
        //查找试题列表
        List<ReadQuestionsVo> ReadQuestionsVoList = orderAnswerService.selectQuestionParsing2(paperId, userId);
        //查找老师评语、试卷得分、试卷名称、试卷答题详情
        OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
        //解析试卷详情
        String userPaperInfo = orderUserPaper.getUserPaperInfo();
        UserPaperAnswerInfo userPaperAnswerInfo = JSONObject.parseObject(userPaperInfo, UserPaperAnswerInfo.class);
        resultMap.put("questionList", ReadQuestionsVoList);
        resultMap.put("paperName", orderUserPaper.getPaperName());
        resultMap.put("paperScore", orderUserPaper.getScore());
        resultMap.put("questionTypeScore", stringStringHashMap);//题型分值
        resultMap.put("stuId", orderUserPaper.getUserId());//学生id
        resultMap.put("paperComment", "");
        if (StringUtils.isNotBlank(orderUserPaper.getComment())) {
            resultMap.put("paperComment", orderUserPaper.getComment());
        }
        resultMap.put("paperDetails", userPaperAnswerInfo);
        return AjaxResult.success(resultMap);
    }

    /**
     * 打分、评语、分数汇总
     *
     * @param paperScoreCommentVo
     * @return
     */
    @PostMapping("/paperScoreComment")
    public AjaxResult paperScoreComment(@RequestBody PaperScoreCommentVo paperScoreCommentVo) {
        //判断试卷是否已经批阅
        List<ReadQuestionsVo> questionScoreAns = paperScoreCommentVo.getQuestionScoreAns();
        //更新表数据 1.试题回答2.试卷回答
        //1.orderanswer
        if (!Objects.isNull(questionScoreAns) && questionScoreAns.size() > 0) {
            for (ReadQuestionsVo readQuestionsVo : questionScoreAns) {
                //    批量更新记录
                OrderAnswer orderAnswer = new OrderAnswer();
                orderAnswer.setQuestionId(readQuestionsVo.getId());
                orderAnswer.setPaperId(paperScoreCommentVo.getPaperId());
                orderAnswer.setUserId(paperScoreCommentVo.getUserId());
                orderAnswer.setScore(readQuestionsVo.getScore());
                orderAnswerService.updateOrderAnswer1(orderAnswer);
            }
        }
        //2.orderUserPaper
        //累加简答题的分数
        int allAns = 0;
        if (!Objects.isNull(questionScoreAns) && questionScoreAns.size() > 0) {
            for (ReadQuestionsVo questionScoreAn : questionScoreAns) {
                allAns += questionScoreAn.getScore();
            }
        }
        OrderUserPaper orderUserPaper = new OrderUserPaper();
        orderUserPaper.setPaperId(paperScoreCommentVo.getPaperId());
        orderUserPaper.setUserId(String.valueOf(paperScoreCommentVo.getUserId()));
        orderUserPaper.setScore(String.valueOf(allAns));
        orderUserPaper.setComment(paperScoreCommentVo.getComment());
        orderUserPaper.setType(1);
        //分数累加 order_user_paper
        int update = orderUserPaperService.update2(orderUserPaper);
        //分数累加 student_answer_details
        int update2 = studentAnswerDetailsService.updateStudentAnswerDetailsByPaperId2StuUserId(paperScoreCommentVo.getPaperId(),
                paperScoreCommentVo.getUserId(), new BigDecimal(orderUserPaper.getScore()), paperScoreCommentVo.getComment());
        //websocket数据更新-首页待批试卷数量减1
        UserInfo userInfo = jwtUtil.getInfoFromToken();
        Long teaUserId = userInfo.getId();
        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
        if (Objects.nonNull(res)) {
            HomeData homeData = (HomeData) res;
            if (homeData.getPaperWait() > 0) {
                homeData.setPaperWait(homeData.getPaperWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        } else {
            //数据初始化
            Object data = homeBuffer.data(String.valueOf(teaUserId));
            HomeData homeData = (HomeData) data;
            if (homeData.getPaperWait() > 0) {
                homeData.setPaperWait(homeData.getPaperWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        }
        return AjaxResult.success("批改成功");
    }

    //---------------------------------------------老师批改作业模块接口---------------------------------------------

    /**
     * @param teaId     老师id
     * @param workName  作业名称
     * @param workState 作业当前状态   作业当前状态   待批改0  已完成1
     * @param classId   班级id
     * @param pageNum   分页参数
     * @param pageSize  分页参数
     * @return
     */
    @GetMapping("/workListByTeacher")
    public AjaxResult workListByTeacher(@RequestParam(value = "teaId", required = false) Integer teaId,
                                        @RequestParam(value = "workName", required = false) String workName,
                                        @RequestParam(value = "workState", required = false) Integer workState,
                                        @RequestParam(value = "classId", required = false) Integer classId,
                                        @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                        @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        //根据参数查询得到的作业列表
        List<SCatalogWork> catalogWorkList = catalogWorkService.workListByTeacher(teaId, workName, workState, classId, pageNum, pageSize);
        //查找试卷关联的班级
        for (SCatalogWork catalogWork : catalogWorkList) {
            //根据作业id 查找分享的班级id和班级名称
            //List<TClass> tClasses = catalogWorkService.selectClassByworkId(catalogWork.getId());
            List<TClass> tClasses = catalogWorkService.selectClassByTopCatalogId(catalogWork.getTopCatalogId());//没有分享表的逻辑
            if (tClasses.size() > 0) {
                //设置考试班级
                StringBuilder tClassNames = new StringBuilder();
                //初始化考生人数
                int examinee = 0;
                //班级id数组集合
                List<Integer> classIdList = new ArrayList<>();
                for (TClass tClass : tClasses) {
                    tClassNames.append(tClass.getClassName() + ",");
                    classIdList.add(tClass.getId());
                }
                if (tClassNames.length() > 0) {
                    tClassNames.deleteCharAt(tClassNames.length() - 1);
                }
                catalogWork.setTClassNames(tClassNames.toString());
                //设置考生人数(查找)  如果classIdList不为空
                /*Integer studentNum = studentService.selectStudentNumByClassId(classIdList);
                orderPaper.setClassSize(studentNum);
                //    考生已提交试卷数量  统计试卷id的个数
                Integer commitPaperNum = orderUserPaperService.selectCommitPaperNum(orderPaper.getId());
                orderPaper.setSubmitnum(commitPaperNum);*/
            }
        }
        PageInfo<SCatalogWork> orderPaperPageInfo = new PageInfo<>(catalogWorkList);
        return AjaxResult.success(orderPaperPageInfo);
    }

    /**
     * 班级id和名称下拉列表获取  批改作业
     *
     * @param teaId 老师id
     * @return
     */
    @GetMapping("/classIdAndNameForWork")
    public AjaxResult classIdAndNameForWork(@RequestParam(value = "teaId", required = false) Integer teaId) {
        //List<TClass> tClasses1 = catalogWorkService.classIdAndNameForWork(teaId);
        List<TClass> tClasses = catalogWorkService.selectClassByTeaId(teaId);//没有分享表的逻辑
        return AjaxResult.success(tClasses);
    }

    /**
     * 查找班级下具体的学生作业列表
     *
     * @param teaWorkId 作业id
     * @param workState 待提交0、批改中1、驳回2、已完成3
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/classWorkList")
    public AjaxResult classWorkList(@RequestParam(value = "teaWorkId", required = false) Integer teaWorkId,
                                    @RequestParam(value = "workState", required = false) Integer workState,
                                    @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                    @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        List<StudentWorkVo> classPaperList = catalogWorkService.classWorkList(teaWorkId, workState, pageNum, pageSize);
        PageInfo<StudentWorkVo> classPaperPageInfo = new PageInfo<>(classPaperList);
        return AjaxResult.success(classPaperPageInfo);
    }

    /**
     * 学生作业详情
     *
     * @param id 学生作业主键id
     * @return
     */
    @GetMapping("/workById")
    public AjaxResult workById(@RequestParam(value = "id", required = false) Integer id) {
        StudentWorkVo studentWork = catalogWorkService.workByworkIdandUserId(id);
        return AjaxResult.success(studentWork);
    }

    /**
     * 打分评语接口
     */
    @PostMapping("/workMarkById")
    public AjaxResult workMarkById(@RequestBody WorkParam workParam) {
        //TODO 判断该作业是否已经进行了批阅(状态判断)
        int i = catalogWorkService.workMarkById(workParam.getId(), workParam.getScore(), workParam.getRemark(), workParam.getState());
        //websocket数据更新-首页待批改作业数量减1
        UserInfo userInfo = jwtUtil.getInfoFromToken();
        Long teaUserId = userInfo.getId();
        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
        if (Objects.nonNull(res)) {
            HomeData homeData = (HomeData) res;
            if (homeData.getWorkWait() > 0) {
                homeData.setWorkWait(homeData.getWorkWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        } else {
            //数据初始化
            Object data = homeBuffer.data(String.valueOf(teaUserId));
            HomeData homeData = (HomeData) data;
            if (homeData.getWorkWait() > 0) {
                homeData.setWorkWait(homeData.getWorkWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        }
        //获取下一份作业的id
        if (i == 1) {
            //TODO 下一个主键的获取
            //查找相同作业、相同班级的作业列表
            List<Integer> studentWorkVoList = catalogWorkService.workListByWorkIdandClassId(String.valueOf(workParam.getId()));
            if (studentWorkVoList != null && studentWorkVoList.size() > 0) {
                studentWorkVoList.removeIf(a -> a.equals(workParam.getId()));
            }
            return AjaxResult.success(studentWorkVoList);
        }
        return AjaxResult.error("批改失败");
    }
}

class WorkParam implements Serializable {
    private Integer id;
    private BigDecimal score;
    private String remark;
    private Integer state;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public BigDecimal getScore() {
        return score;
    }

    public void setScore(BigDecimal score) {
        this.score = score;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }
}





